import json
import random
import time
import redis
import requests
from flask import make_response, redirect
from tools.my_jwt import jj
from tools.captcha.captcha import captcha
from tools.comm.comm import sendMsg
from tools.myredis import r
from application.models.users.user import *
from flask import Blueprint,request,jsonify
user_blue = Blueprint("userblue",__name__)

@user_blue.route('/getcode')
def get_img():
    name,text,img=captcha.generate_captcha()
    uuid=request.args.get('uuid')
    r.str_add(uuid,text)
    cls = redis.Redis(host='127.0.0.1')
    print(">>>>>>>>>>>>>>>>",cls.get(uuid))
    res=make_response(img)
    res.headers['Content-Type']="image/jpg"
    return res


@user_blue.route('/sendSmsCode',methods=['post'])
def sendSmsCode():
    data = request.data
    if data:
        # 获取3个参数
        data = json.loads(data)
        uuid = data['uuid']
        piccode = data['piccode']
        print(piccode,'>>>>>>>>>>>>>>>>')
        mobile = data['mobile']
        # redis中获取图片验证码
        value = r.str_get(uuid)
        # 对redis中获取的图片验证码解析
        value1 = value.decode()
        print(value1)
        # 如果图片验证码存在
        if value:
            # 将前端输入的验证码和图片验证码转为大小写 做对比
            if piccode.lower()==value1.lower():
                # 把redis里面存的手机号获取出来 然后赋值给mcode
                mcode = r.str_get(mobile)
                # 如果手机号存在
                if mcode:
                    return jsonify({'code':10012,'msg':'一分钟内不能重复发'})
                # 调用random生成随机数
                scode = random.randint(10000,99999)
                # 把容连云赋值到flag里面
                flag = sendMsg(mobile,scode)
                # 如果flag存在
                if flag:
                    # 就把手机号加入到redis里面 一分钟
                    r.str_setex(mobile,scode,60)
                    # 判断完图形验证码之后 删除redis里面的图形验证码
                    r.del_key(uuid)
                    return jsonify({'code':200,'msg':'发送成功'})
                else:
                    return jsonify({'code':10013,'msg':'发送验证码错误'})
            else:
                return jsonify({'code':10011,'msg':'图片验证码错误'})

        else:
            return jsonify({'code':10010,'msg':'图片验证码不存在'})


@user_blue.route('/login',methods=['POST'])
# 注册登录接口
def login():
    # 获取前端返回的数据
    data = request.data
    # 如果存在
    if data:
        # 把获取到的data 转化json格式赋值到data里面
        data = json.loads(data)
        # 获取参数
        mcode = data['code']
        mobile = data['mobile']
        # 获取到redis里面存储的手机号
        code = r.str_get(mobile)
        # 如果手机号存在
        if code:
            #
            if int(code)==int(mcode):
                user = User.query.filter(User.mobile==mobile).first()
                if user:
                    r.del_key(mobile)
                else:
                    u = User(mobile=mobile,nikename=mobile)
                    db.session.add(u)
                    db.session.commit()
                    user = User.query.filter(User.mobile==mobile).first()
                # 用户信息生成jwt token
                token = jj.jwt_encode(data={'data':{'uid':user.id,'exp':int(time.time())}})
                return jsonify({'code':200,'token':token,'userid':user.id})
            else:
                return jsonify({'code':10021,'msg':'验证码错误'})
        else:
            return jsonify({'code':10020,'msg':''})

# 获取weibo地址
@user_blue.route('/sf_login')
def getwburl():
    client_id = "3674019597"
    redirect_uri = "http://127.0.0.1:8000/user/weiboCallback/"
    url = "https://api.weibo.com/oauth2/authorize?client_id=%s&redirect_uri=%s&response_type=code" % (
        client_id, redirect_uri)
    return jsonify({"code":200,"url":url})

# weibo回调接口
@user_blue.route('/user/weiboCallback/')
def weiboCallback():
    # 获取code
    code = request.args.get("code")
    # 向access_token接口发送post请求
    data = {"client_id": '3674019597', "client_secret": "7ae99bc0d54ead29fc8d1b9fabd78587",
            "grant_type": "authorization_code",
            'redirect_uri': 'http://127.0.0.1:8000/user/weiboCallback/', 'code': code}
    res = requests.post('https://api.weibo.com/oauth2/access_token', data=data)
    # 根据返回结果操作
    # 获取token和uid
    message = json.loads(res.text)
    token = message['access_token']
    uid = message['uid']
    # 查询数据库中是否存在，如果存在用户信息生成jwt token 返回
    sql = 'select user.id from user inner join sf_login on user.id=sf_login.userid where sf_login.uid=%s'%(uid)
    user = db.session.execute(sql)
    if user:
        for i in user:
            data = {'data':{'userid':i[0],'exp':int(time.time())}}
            token = jj.jwt_encode(data)
            return redirect("http://localhost:8080/#/updateToken?userid="+str(i[0]) + "&token=" + token)
    # 不存在跳转到vue绑定页面，token uid 传递过去
    return redirect("http://localhost:8080/#/banding?uid="+uid+"&token="+token)

from application.models.users.user import SfLogin
# 绑定手机号
@user_blue.route('/bandMobile',methods=['POST'])
def bandMobile():
    data = json.loads(request.data)
    mobile = data['mobile']
    uid = data['uid']
    token = data['token']
    print(mobile,'>>>>>>>>>>>>>>>>>>>>>>>>>..')
    # 先查询用户表，如果手机号存在，获取userid,写入三方登录表，生成token返回
    user = User.query.filter(User.mobile==mobile).first()
    print(user)
    if not user:
        # 添加用户
        u = User(mobile=mobile,nikename=mobile)
        print(u)
        db.session.add(u)
        db.session.commit()
        # 获取用户信息
        user = User.query.filter(User.mobile==mobile).first()
    sfuser = SfLogin(userid=user.id, webfrom='wb', uid=uid, token=token)
    db.session.add(sfuser)
    db.session.commit()
    # 如果不存在，写入user表
    # 获取userid,写入三方登录表，生成token返回
    data = {'data':user.id,'exp':int(time.time())}
    token = jj.jwt_encode(data)
    return jsonify({'userid':str(user.id),'token':token})


# 测试
import pymysql
from tools.comm.comm import get_ali_object
@user_blue.route('/text')
def text():
    orderon = '1234500'
    pay = get_ali_object()
    query_params = pay.direct_pay(
        subject='test',  #"充值服务",  # 商品简单描述
        out_trade_no=str(orderon), # 用户购买的商品订单号（每次不一样） 20180301073422891
        total_amount=float(1.00),  # 交易金额(单位: 元 保留俩位小数)
    )
    pay_url = "https://openapi.alipaydev.com/gateway.do?{0}".format(query_params)  # 支付宝网关地址（沙箱应用）
    return jsonify({
        'code': 200,
        'url': pay_url
    })
    # alipay = get_ali_object()
    # # 生成支付的url
    # query_params = alipay.direct_pay(
    # subject="test",  # 商品简单描述
    # out_trade_no="asfasf"+str(time.time()),  # 用户购买的商品订单号（每次不一样） 20180301073422891
    # total_amount=100,  # 交易金额(单位: 元 保留俩位小数)
    # )
    # pay_url = "https://openapi.alipaydev.com/gateway.do?{0}".format(query_params)  # 支付宝网关地址（沙箱应用）
    # return redirect(pay_url)


from application.models.users.user import VipRecord
# 购买vip生成订单
@user_blue.route('/buy',methods=['POST'])
def buy():
    # 获取参数
    data = json.loads(request.data)
    userid = data['userid']
    year = data['year']
    money = 200
    # 生成订单
    tmoney = money * int(year)
    order_no = str(int(time.time()))+str(userid)+str(random.randint(100,999))
    Viprecord = VipRecord(order_no=order_no,userid=userid,year=year,money=tmoney,active_money=tmoney,status=1)
    db.session.add(Viprecord)
    db.session.commit()
    pay = get_ali_object()
    query_params = pay.direct_pay(
        subject='test',  # "充值服务",  # 商品简单描述
        out_trade_no=str(order_no),  # 用户购买的商品订单号（每次不一样） 20180301073422891
        total_amount=float(1.00),  # 交易金额(单位: 元 保留俩位小数)
    )
    pay_url = "https://openapi.alipaydev.com/gateway.do?{0}".format(query_params)  # 支付宝网关地址（沙箱应用）
    return jsonify({
        'code': 200,
        'url': pay_url
    })


# 添加支付宝流水号数据
from application.models.users.user import Vip
#支付回调
@user_blue.route("/callback")
def callback():
    data = request.args
    datames = {k:v for k,v in data.items()}
    #删除字典中key为sign的记录
    sign = datames.pop('sign')
    #鉴权
    pay = get_ali_object()
    flag = pay.verify(datames,sign)
    if flag == True:
        #订单号
        order_no = datames["out_trade_no"]
        order_no_index = order_no.split(",")
        #支付宝流水号
        transaction_no = datames["trade_no"]
        #事务处理
        try:
            if order_no_index[1] == 1:
                #订单号更新vip订单表
                record = VipRecord.query.filter(VipRecord.order_no==order_no).first()
                record.status=2
                record.transaction_no=transaction_no
                db.session.add(record)
                #更新用户表
                user_info = User.query.filter(User.id==record.userid).first()
                user_info.level = 2
                print(user_info.id)
                #更新vip表
                vip = Vip.query.filter(Vip.userid==record.userid,status=1).first()
                if vip is not None:
                    #结束时间+购买年限
                    etime = vip.e_time.split("-")
                    year = int(etime[0])+int(record.year)
                    vip.e_time = year
                    print(">>><<<")
                else:
                    nowyear = datetime.date.strftime(datetime.datetime.now(),"%Y-%m-%d %H:%m:%s")
                    etime = nowyear.split("-")
                    year = int(etime[0])+int(record.year)
                    print(year)
                    str1 = "-"
                    retime = str1.join(etime)
                    vip = Vip(userid=record.userid,s_time=datetime.datetime.now(),e_time=retime)
                    db.session.add(vip)
                    print("<<<>>>")
                db.session.commit()
            if order_no_index[1] == 2:
                # 订单号更新订单表
                record = Orders.query.filter(Orders.number == order_no).first()
                record.status = 3
                db.session.commit()
                print("///////////")
        except:
            db.session.rollback()
    else:
        print("鉴权失败")
    return redirect('http://localhost:8080/#/')


from application.models.users.user import Tags,Ctype,CourseType
# 获取 类别 标签 数据
@user_blue.route('/getTags')
def getTags():
    tags = Tags.query.all()
    tagslist = [{'id':i.id,'name':i.name}for i in tags]
    ctype = Ctype.query.all()
    ctypelist = [{'id':i.id,'name':i.name}for i in ctype]
    course = CourseType.query.all()
    courselist = [{'id':i.id,'name':i.name}for i in course]
    return jsonify({'code':200,'tags':tagslist,'ctype':ctypelist,'course':courselist})

from db import dp
# 获取标签下的数据
@user_blue.route('/getid')
def getRoleResoure():
    id = request.args.get("id")
    print("id", id)
    if not id:
        return jsonify({'code':400,'msg':'数据不存在'})
    sql = "select * from course as c inner join course_tag as ct on ct.courseid=c.id where ct.tagid=" + id
    res = dp.find_all(sql)
    print(res)
    return jsonify({"code": 200, 'data': res})


from flask_restful import reqparse
# 获取 免费、全部、vip数据
@user_blue.route('/getvip',methods=['POST'])
def post():
    req = reqparse.RequestParser()
    req.add_argument('id')
    req.add_argument('userid')
    args = req.parse_args()

    if not args['id']:
        return jsonify({'code': 400, 'msg': '数据不存在'})
    # 全部
    if int(args['id']) == 1:
        qsql = "select * from course where is_vip=0"
        qres = dp.find_all(qsql)
        return jsonify({'code': 200, 'getvip': qres})
    # 免费
    if int(args['id']) == 2:
        sqlq = "select * from course where is_vip=0"
        user = dp.find_all(sqlq)
        return jsonify({'code': 200, 'getvip': user})
    # # 会员
    sql = 'select * from user where id=%d and level=1' % int(args['userid'])
    ress = dp.find_all(sql)
    if ress:
        if int(args['id']) == 3:
            sqll = 'select * from course where is_vip=1'
            res = dp.find_all(sqll)
            return jsonify({'code': 200, 'msg': 'ok', 'getvip': res})
    else:
        return jsonify({'code': 400, 'msg': '不是会员无法访问'})



# 获取 是否发布数据
@user_blue.route('/getpub')
def GetIs_publish():
    id = request.args.get("id")
    print("id", id)
    if not id:
        return jsonify({'code':400,'msg':'数据不存在'})
    sql = "select * from course where is_publish=%d"%int(id)
    res = dp.find_all(sql)
    print(res)
    return jsonify({"code": 200, 'data': res})


# 获取 最新、最热数据
@user_blue.route('/hew_hot')
def Get_hew_hot():
    type = request.args.get("type")
    print("id", id)
    if not type:
        return jsonify({'code':400,'msg':'数据不存在'})
    if type == 'hew':
        sql = "select * from course order by create_time desc"
        res = dp.find_all(sql)
        print(res)
        return jsonify({"code": 200, 'data': res})
    else:
        sql1 = 'select * from course order by views desc'
        ress = dp.find_all(sql1)
        print(ress)
        return jsonify({"code": 200, 'data': ress})


# 获取章节
@user_blue.route('/getjie')
def Get_Jie():
    id = request.args.get("id")
    print(id,11111111111111111111111111111111)
    if not id:
        return jsonify({'code':400,'msg':'数据不存在'})
    sql = "select * from jie where jie.courseid=%d"%int(id)
    res = dp.find_all(sql)
    print(res)
    return jsonify({"code": 200, 'data': res})

# 获取课程所有数据
@user_blue.route('/get_course')
def Get_course():
    id = request.args.get("id")
    print(id,11111111111111111111111111111111)
    if not id:
        return jsonify({'code':400,'msg':'数据不存在'})
    sql = "select * from course where id=%d"%int(id)
    res = dp.find_all(sql)
    print(res)
    return jsonify({"code": 200, 'data': res})




